﻿using BarcodeScanner;
using QDPay.Bus;
using QDPay.Bus.domain.json;
using QDPay.Bus.util;
using QDPay.code;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows.Forms;

namespace QDPay
{
    public partial class frmPay : FormBase
    {
        int oid = 0;
        string payType = "";
        QDPays pay = new QDPays();
        Orders orders = new Orders();
        ScanerHook listener;

        public frmPay()
        {
            InitializeComponent();
            //扫码监听
            listener = new ScanerHook();
            listener.ScanerEvent += Listener_ScanerEvent;
            listener.Start();

            //会员初始化
            Init();
        }

        private void frmPay_Load(object sender, EventArgs e)
        {
        }

        private void frmPay_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (listener != null)
                listener.Stop();
            CloseForm(this);
        }

        decimal oldMoney = 0;
        private void btnWxPay_Click(object sender, EventArgs e)
        {
            txtCode.Text = "";
            decimal money = 0;
            decimal.TryParse(txtMoney.Text, out money);
            txtMoney.Text = money.ToString();
            oldMoney = money;

            oid = new Random().Next();
            Echo("请扫码完成付款");
            txtCode.Focus();

            //payType = "FACEPAY";    //刷脸测试
        }

        private void SetMoney_Click(object sender, EventArgs e)
        {
            Button btn = sender as Button;
            int tag = Convert.ToInt32(btn.Tag);
            if (tag == -1)
            {
                //删除
                if (txtMoney.Text.Length > 0)
                    txtMoney.Text = txtMoney.Text.Substring(0, txtMoney.Text.Length - 1);
                if (txtMoney.Text == "")
                    txtMoney.Text = "0";
            }
            else if (tag == -2)
            {
                //小数点
                if (txtMoney.Text.IndexOf(".") == -1)
                    txtMoney.Text = txtMoney.Text + ".";
            }
            else
            {
                //数字
                if (txtMoney.Text == "0")
                    txtMoney.Text = "";
                txtMoney.Text = txtMoney.Text + btn.Tag;
            }
            Echo("");
        }

        #region 限制输入金额

        bool isInput = false;   //是否允许输入
        private void txtMoney_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {

            //限制小键盘才能输入金额，防止扫码枪输入
            if ((e.KeyValue >= 96 && e.KeyValue <= 105) ||      //小键盘数字键
                e.KeyValue == 110 || e.KeyValue == 190 ||       //小数点
                e.KeyValue == 8 || e.KeyValue == 46)            //左删除、右删除
            {
                isInput = true;
                Echo("");
            }
            else if (e.KeyValue >= 48 && e.KeyValue <= 57)
            {
                Echo("请点击数字的方式输入金额");
            }
            else
            {
                isInput = false;
            }
        }

        private void txtMoney_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!isInput)
                e.Handled = true;
        }
        #endregion

        #region  提交支付

        private void Listener_ScanerEvent(ScanerHook.ScanerCodes codes)
        {
            txtCode.Focus();
            txtCode.Text = codes.Result.Trim();

            if (txtMoney.Text.Contains(codes.Result))
                txtMoney.Text = txtMoney.Text.Replace(codes.Result, "");

            ThreadPool.QueueUserWorkItem(new WaitCallback(SubmitPay), codes.Result.Trim());
            //SubmitPay(null);
        }

        private void SubmitPay(object authCode)
        {
            decimal money = 0;
            decimal.TryParse(txtMoney.Text, out money);
            int createUid = Session.StoreEmployee.CreateUid;
            string code = authCode.ToString();

            if (!PayCheck(money, code)) return;
            oid = 0;
            Echo("正在提交...");

            try
            {
                //刷脸支付
                if (payType == "FACEPAY")
                {
                    //获取付款用户
                    int uid = pay.CodeToUid(createUid, code);
                    //创建订单
                    int pay_oid = orders.CreateOrder(uid, createUid, money, Session.StoreEmployee.Id);
                    if (pay_oid < 1) throw new Exception("订单创建失败，请重试");

                    pay.MicroPay(createUid, pay_oid, money, code);
                    //pay.FacePay(createUid, pay_oid, money, code);
                }
                else
                {
                    //获取付款用户
                    int uid = pay.CodeToUid(createUid, code);
                    //创建订单
                    int pay_oid = orders.CreateOrder(uid, createUid, money, Session.StoreEmployee.Id);
                    if (pay_oid < 1) throw new Exception("订单创建失败，请重试");

                    //发起刷码支付
                    var payResponse = pay.MicroPay(createUid, pay_oid, money, code);
                    //检查结果
                    var result = pay.CheckPay(payResponse, createUid);
                    Echo(result);

                    LogUtil.WriteLog(string.Format("pay callback: oid:{0}, uid={1},status:{2}\r\n {3}",
                        pay_oid, uid, result, pay.SerializeObject(payResponse)));
                }
            }
            catch (Exception ex)
            {
                LogUtil.WriteLog("err", "支付系统异常:" + ex.ToString());
                Echo("支付失败," + ex.Message);
            }
        }

        List<string> codeList = new List<string> { "10", "11", "12", "13", "14", "15" };
        private bool PayCheck(decimal money,string code)
        {
            if (money <= 0)
            {
                Echo("金额必须大于0"); return false;
            }
            //授权码：18位纯数字，以10、11、12、13、14、15开头
            if (code.Length != 18)
            {
                LogUtil.WriteLog("err", "授权码长度错误:" + txtCode.Text);
                Echo("授权码长度错误"); return false;
            }
            if (!codeList.Contains(code.Substring(0, 2)))
            {
                LogUtil.WriteLog("err", "授权码格式错误:" + txtCode.Text);
                Echo("授权码格式错误"); return false;
            }
            if (Session.StoreEmployee == null)
            {
                Echo("商家登录后才能收银"); return false;
            }
            if (oid == 0)
            {
                Echo("请选择支付方式"); return false;
            }

            //if (oid < 1) return false;
            return true;
        }
        #endregion

        #region 私有

        void Init()
        {
            this.txtMoney.AutoSize = false;
            this.txtMoney.Height = 40;
            this.txtCode.Visible = false;
            this.lblMsg.Text = "";
        }

        void Echo(string msg)
        {
            if (lblMsg.InvokeRequired)
            {
                lblMsg.Invoke((MethodInvoker)(() =>
                {
                    lblMsg.Text = msg;
                }));
            }
            else
            {
                lblMsg.Text = msg;
            }
        }

        #endregion

   
    }
}